<?php

class AppController extends Controller {

    var $helpers = array('Form', 'Html', 'Javascript');
    var $uses = array("User");
    var $ruleGrupos = array();
    var $ruleProcesos = array();
    var $rulesRolesGrupo = array();
    var $rolesPermitidosParaGrupo = array();

    private $_authController = 'users';
    private $_authLoginAction = 'login';
    private $_authLoginView = 'index';
    private $_authLogoutAction = 'logout';

    function beforeRender() {
        $this->set("hostname", Configure::read("hostname"));
        $this->set("ckfinderPath", Configure::read("hostname"));
        $this->set("ckfinderImgPath", Configure::read("hostname"));
    }
    function getUserId(){
        return $this->Session->read("ss_user_id");
    }
    function isLogged(){
        $uid = $this->Session->read("ss_user_id");
        if(!empty($uid))    return true;
        else return false;
    }
    /*
     * Fucnion de autenticacion que permite hacer login y validar permisos de accesos a los distintos modulos y paginas mediante el rol asociado
     */
    function preDispatcher() {
        $loginView = $this->_authController.'/'.  $this->_authLoginView;
        $controller = $this->params["controller"];
        $action =  $this->params["action"];
        if(!$this->isLogged()){
            if($controller !== $this->_authController){
                $this->redirect($loginView);
            }
            elseif($controller === $this->_authController){
                if($action === $this->_authLoginAction){
                    $uid = $this->data["uid"];
                    $pass = $this->data["pass"];
                    if($this->User->login($uid,$pass)){
                        $success = true;
                        $credentials = array(
                            'user_id' => $uid,
                            'logged_in' => $success
                        );
                    }
                    else{
                        $this->redirect($loginView);
                    }
                }
                elseif($action === $this->_authLogoutAction){
                    $this->autoRender = false;
                    $this->Session->destroy();
                    echo "sesion eliminada con exito";
                }
            }
            else{

            }
        }
        else{
            
        }
    }

    function beforeFilter() {
        $this->procesosFormadores = Configure::read('procesosFormadores');
        //$this->preDispatcher();
    }

    function outJson($response) {
        Configure::write('debug', 0);
        $this->autoRender = false;
        $this->autoLayout = false;
        $this->layout = 'ajax';
        $this->RequestHandler->setContent('json', 'application/json');
        echo json_encode($response);
        exit();
    }

    function outDebug() {
        Configure::write('debug', 2);
        $this->autoRender = false;
    }

}
?>
